package cn.thinkluck.pattern.proxy.dynamic.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * aop切面
 *
 * @Author liutao
 * @DateTime 2024/7/20 下午4:59
 */
@Component
@Aspect
@Slf4j
public class CacheAspectj {
    @Pointcut("execution(* cn.thinkluck.pattern.proxy.dynamic.aop.DataQuery.query(..))")
    public void pointcut() {
    }

    @Around("pointcut()")
    public String around(ProceedingJoinPoint joinPoint) throws Throwable {
        String queryKey = (String) joinPoint.getArgs()[0];
        //1. 查询缓存，命中则返回
        String data = Cache.CACHE.get(queryKey);
        if (data != null) {
            log.info("命中缓存，返回数据：{}", data);
            return data;
        }
        //2. 缓存未命中，查询数据库，并将结果存入缓存
        log.info("缓存未命中，查询数据库");
        data = (String) joinPoint.proceed();
        Cache.CACHE.put(queryKey, data);
        return data;
    }
}
